﻿using System;
using System.Text;
using System.Security.Cryptography;

namespace System.AWSServices.Shared
{
    public class AWSSecurity
    {
        private static string TIMESTAMP_FORMAT = "yyyy-MM-dd\\THH:mm:ss.fff\\Z";

        public static DateTime TimeStamp
        {
            get
            {
                DateTime dateTime = DateTime.Now;
                return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day,
                                     dateTime.Hour, dateTime.Minute, dateTime.Second,
                                     dateTime.Millisecond,
                                     DateTimeKind.Local
                                   );
            }
        }

        private static string FormatAsISO8601(DateTime datetime)
        {
            return datetime.ToUniversalTime().ToString(TIMESTAMP_FORMAT, System.Globalization.CultureInfo.InvariantCulture);
        }

        public static string CreateSignature(string accessKey, string service, string method, DateTime timestamp)
        {
            string canonicalString = service + method + FormatAsISO8601(timestamp);
            Encoding encode = new UTF8Encoding();
            HMACSHA1 signature = new HMACSHA1(encode.GetBytes(accessKey));
            return Convert.ToBase64String(signature.ComputeHash(encode.GetBytes(canonicalString.ToCharArray())));
        }
    }
}
